<template>
  <a-tabs v-model:activeKey="activeKey" hide-add type="editable-card" @edit="onEdit" @tabClick="handleTabClick">
    <a-tab-pane v-for="tab in tabList" :key="tab.path" class="home-tab" :closable="tab.closable">
      <template #tab>
        <span>
          <HomeOutlined v-if="tab.path === isHome" />
          <template v-else>
            {{ tab.title }}
          </template>
        </span>
      </template>
    </a-tab-pane>
  </a-tabs>
</template>

<script lang="ts">
import { defineComponent, computed } from 'vue'
import { useStore } from 'vuex'
import { HomeOutlined } from '@ant-design/icons-vue'

export default defineComponent({
  components: {
    HomeOutlined
  },
  setup() {
    const store = useStore()
    const isHome = '/'
    const tabList = computed(() => store.state.tabsView.tabList)
    const activeKey = computed({
      get: () => store.state.tabsView.activeKey,
      set: val => val
    })

    return {
      tabList,
      isHome,
      activeKey,
    }
  },
  methods: {
    /**
     * 点击 tab
     */
    handleTabClick(path) {
      this.$router.push(path)
      this.$store.commit('tabsView/SET_ACTICVE_KEY', path)
      this.$store.commit('tabsView/SET_OPEN_KEYS', ['/' + path.split('/')[1]])
    },
    onEdit(targetKey, action) {
      this[action](targetKey)
    },
    /**
     * 删除 tab
     */
    remove(targetKey: string) {
      this.$store.commit('tabsView/REMOVE_TAB', targetKey)
      this.$store.commit('tabsView/SET_SELECTED_KEYS', targetKey)
      this.$router.push(this.activeKey)
    },
  },
})
</script>
